import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpServer, HttpStatus, Logger } from "@nestjs/common";
import * as requestIp from 'request-ip';
import { QueryFailedError } from "typeorm";

@Catch()
export class AllExceptionFilter implements ExceptionFilter {
  constructor(
    private readonly httpAdapter: HttpServer
  ) { }
  catch(exception: unknown, host: ArgumentsHost) {
    // const { httpAdapter } = this.httpAdapterHost
    const ctx = host.switchToHttp();
    const request = ctx.getRequest();
    const response = ctx.getResponse();
    const httpStatus = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
    let errorMsg
    console.log({ exception })
    let responseBody
    if (exception instanceof HttpException) {
      errorMsg = exception.getResponse() || '服务器内部错误';
      responseBody = {
        headers: request.headers,
        query: request.query,
        params: request.params,
        body: request.body,
        statusCode: httpStatus,
        timestamp: new Date().toISOString(),
        path: request.url,
        // 还可以加入一些用户信息
        // IP信息
        ip: requestIp.getClientIp(request),
        exceptioin: exception.name,
        error: errorMsg,
      }
      Logger.error(responseBody, exception.stack, 'ExceptionFilter')
    }
    
    this.httpAdapter.reply(response, responseBody, httpStatus)
  }

}